#pragma once

#include <iostream>
#include "Log.hpp"
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <strings.h>
#include <string.h>
#include <error.h>
#include <functional>

enum
{
    Socket_Err = 1,
    Bind_Err
};

//端口号, IP地址
uint16_t defaultport = 8080;
string defalutip = "0.0.0.0";

typedef function<string(const string&)> func_t;

class UdpServer
{
public:
    UdpServer(const uint16_t& port = defaultport, const string& ip = defalutip)
        :sockfd_(0)
        ,ip_(ip)
        ,port_(port)
        ,isrunning_(false)
    {}

    void Init()
    {
        //创建udp, socket;
        sockfd_ = socket(AF_INET, SOCK_DGRAM, 0);
        if(sockfd_ < 0)
        {
            log(Fatal, "socket create error, socket: %d", sockfd_);
            exit(Socket_Err);
        }
        log(Info, "socket create success, sockfd: %d", sockfd_);

        //绑定socket;本地服务端socket
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        //从主机字节序转网络字节序;
        local.sin_port = htons(port_);
        //将主机地址转网络地址;
        local.sin_addr.s_addr = inet_addr(ip_.c_str());

        //绑定本地主机;
        if(bind(sockfd_, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            log(Fatal, "bind error, error: %d, err string: %s", error, strerror(errno));
            exit(Bind_Err);
        }
        log(Info, "bind success, errno: %d, err string: %s", errno, strerror(errno));
    }

    void Run(func_t func)
    {
        isrunning_ = true;
        char inbuffer[1024];

        while(isrunning_)
        {
            //客户端socket
            struct sockaddr_in client;
            socklen_t len = sizeof(client);

            //收到client的数据, recvfrom就是从socket里面接收服务端数据;
            ssize_t n = recvfrom(sockfd_, inbuffer, sizeof(inbuffer) - 1, 0, (struct sockaddr *)&client, &len);
            if(n < 0)
            {
                log(Warning, "recvfrom error, errno: %d, err string: %s", errno, strerror(errno));
                continue;
            }


            inbuffer[n] = 0;
            string info = inbuffer;
            string echo_string = func(info);
            //将收到的数据再重新发回去.
            cout << echo_string << endl;
            //通过socket发送一个数据给client端
            sendto(sockfd_, echo_string.c_str(), sizeof(echo_string), 0, (const struct sockaddr *)&client, len);
        }
    }

    ~UdpServer()
    {
        if(sockfd_ > 0)
            close(sockfd_);
    }
private:
    int sockfd_;
    string ip_;
    uint16_t port_;
    bool isrunning_;
};